package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

/**
 * <p>
 * .
 *
 * @author o_o
 * @date 2024-05-13
 */
public class LoggerServiceLoader {
    private static final LoggerServiceLoader SERVICE = new LoggerServiceLoader();

    private final Logger logger;

    private final List<Logger> loggerList;

    public LoggerServiceLoader() {
        // 加载所有实现了Logger接口的类
        ServiceLoader<Logger> loader = ServiceLoader.load(Logger.class);
        List<Logger> list = new ArrayList<>();
        for (Logger log : loader) {
            list.add(log);
        }
        this.loggerList = list;
        // 只取一个Logger的实现类
        if (!list.isEmpty()) {
            this.logger = list.get(0);
        } else {
            this.logger = null;
        }
    }

    public static LoggerServiceLoader getService() {
        return SERVICE;
    }

    public void info(String msg) {
        if (logger == null) {
            System.err.println("info 中没有发现 Logger 服务提供者");
        } else {
            logger.info(msg);
        }
    }

    public void debug(String msg) {
        if (loggerList.isEmpty()) {
            System.err.println("debug 中没有发现 Logger 服务提供者");
        }
        loggerList.forEach(log -> log.debug(msg));
    }
}
